<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/31/24
 * Time: 10:36 AM
 */

namespace app\common\command;

use app\common\model\media\Media;
use app\common\model\media_account\MediaAccount;
use app\common\model\risk_report\RiskReport;
use app\common\service\media\KsService;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\console\Command;

class PullHourKsReport extends Command
{
    protected function configure()
    {
        $this->setName('pull_hour_ks_report')
            ->addOption('date', null, Option::VALUE_OPTIONAL, '拉取日期')
            ->addOption('hour', null, Option::VALUE_OPTIONAL, '拉取小时')
            ->setDescription('拉取快手媒体风控成本报表');
    }


    /**
     * 拉取快手报表
     *
     * @param Input $input
     * @param Output $output
     * @return bool|int|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        // 获取需要拉取报表的媒体账户
        $accounts = MediaAccount::with('link')
            ->where([
                ['media_id', '=', Media::SOURCE_KS],
                ['status', '=', 1],
                ['promotion_link_id', '<>', 0]
            ])->select();

        if ($accounts->isEmpty()) {

            return false;
        }
        $output->writeln('开始拉取快手媒体风控报表成本，共计：' . $accounts->count() . '条');

        // 拉取日期
        if ($input->hasOption('date')) {
            $pullDate = $input->getOption('date');
        } else {
            $pullDate = date('Y-m-d');
        }

        $pullHour = date('H');

        foreach ($accounts as $account) {
            $service = new KsService($account->media_auth_id);
            if (!$link = $account->link ?? []) {
                continue;
            }
            $costMoney     = $service->getAdvertiserReport($account->auth_advertiser_id, $account->advertiser_id, $pullDate);
            $report        = RiskReport::where([
                'promotion_link_id' => $link->id, 'count_date' => $pullDate, 'hour' => $pullHour
            ])->findOrEmpty();
            $lastCostMoney = $this->getLastCostMoney($pullDate, $pullHour, $link->id);
            $diffCostMoney = $costMoney - $lastCostMoney;
            if ($report->isEmpty()) {
                $adId = MediaAccount::where('promotion_link_id', $link->id)->order('id', 'desc')->value('advertiser_id');
                RiskReport::create([
                    'count_date'        => $pullDate,
                    'hour'              => $pullHour,
                    'promotion_link_id' => $link->id,
                    'pitcher_id'        => $link->admin_id ?? 0,
                    'advertiser_id'     => $adId ?? 0,
                    'cost_money'        => ($diffCostMoney <= 0) ? 0 : $diffCostMoney,
                ]);
            } else {
                if ($diffCostMoney > 0) {
                    $report->cost_money = $diffCostMoney;
                    $report->save();
                }
            }
        }

        $output->writeln('拉取快手媒体风控报表成本完成');
    }


    /**
     * 获取过去成本
     *
     * @param $countDate
     * @param $hour
     * @param $lastHour
     * @param $linkIdt
     * @return int
     */
    private function getLastCostMoney($countDate, $hour, $linkId)
    {
        if ($hour == '00' || $hour == 0) {

            return 0;
        } else {
            return RiskReport::where([
                    'count_date'        => $countDate,
                    'promotion_link_id' => $linkId
                ])
                    ->where('hour', '<>', $hour)
                    ->sum('cost_money') ?? 0;
        }
    }

}
